<?php
namespace app\wxapp\service;
use app\common\util\CacheKey;
use think\facade\Cache;
use think\facade\Db;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/4 0004
 * Time: 19:52
 */
class CategoryService{



    public function tree(){
        $list = Db::table('category')->select()->toArray();
        //这里只有两级 因此不需要递归
        $firstLevel = [];
        $secondLevel = [];
        foreach( $list as $key => $val ){
            if($val['parent_id'] == 0){
                array_push($firstLevel,$val);
            }else{
                if(!isset($secondLevel[$val['parent_id']])){
                    $secondLevel[$val['parent_id']] = [];
                }
                array_push($secondLevel[$val['parent_id']],$val);
            }
        }
        foreach($firstLevel as $key => $val ){
            if(isset($secondLevel[$val['id']])){
                $firstLevel[$key]['sub'] = $secondLevel[$val['id']];
            }else{
                $firstLevel[$key]['sub'] = [];
            }
        }
        return $firstLevel;
    }



    public function all(){
        return Db::table("category")->column("name,id","id");
    }

    /**
     * 这个页面每个人都是看到的一样的，可以用缓存  后台改变数据的时候 清除缓存
     * 获取每个二级栏目的最新视频或者专栏
     * @param $ids
     * @return mixed
     */
    public function getNewest($ids){
        $storeKey = CacheKey::WXAPP."#".implode("-",$ids);
        $result = Cache::get($storeKey);
        if(!empty($result)){
            Cache::delete($storeKey);
            return $result;
        }
        $result = [];
        //一次取是不好取出的 只有分开取了
        foreach($ids as $key => $categoryId ){
            $list = $this->getTopicNewestByCate($categoryId);
            $diff = 6 - count($list);
            $videoList = $this->getVideoNewestByCate($categoryId,$diff);
            $result[$categoryId] = [
              'topic'=>$list,'video'=>$videoList
            ];
        }
        Cache::set($storeKey,$result);
        return $result;
    }

    private function getTopicNewestByCate($categoryId){
        //先取专栏3个 如果不够 视频凑足 一个六个，如果还是不够 那就不够
        return Db::table("topic")->where(['category_id'=>$categoryId])->order('id','desc')->limit(0,3)->select();
    }

    private function getVideoNewestByCate($categoryId,$len){
        return Db::table('video_list')->where(['category_id'=>$categoryId])->order('id','desc')->limit(0,$len)->select();
    }

}
